package handler

import (
	"2212b/happy_orange/api/handler/request"
	"2212b/happy_orange/internal/dao"
	"2212b/happy_orange/internal/model"
	"github.com/gin-gonic/gin"
	"net/http"
)

func AddFriend(c *gin.Context) {
	var req request.AddFriend

	if err := c.ShouldBind(&req); err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code": 100000,
			"msg":  "验证失败",
			"data": err.Error(),
		})
		return
	}
	var user model.User
	dao.GetOneById(req.UserTwo, &user)
	if user.Id == 0 {
		c.JSON(http.StatusOK, gin.H{
			"code": 100000,
			"msg":  "用户不存在",
			"data": nil,
		})
		return
	}
	if dao.IsFriend(c.GetUint("userId"), req.UserTwo) {
		c.JSON(http.StatusOK, gin.H{
			"code": 100000,
			"msg":  "已经成为好友不需要申请",
			"data": nil,
		})
		return
	}
	dao.Create(&model.Friend{
		UserOne: c.GetUint("userId"),
		UserTwo: req.UserTwo,
		Status:  1,
	})
	c.JSON(http.StatusOK, gin.H{
		"code": http.StatusOK,
		"msg":  "成功",
		"data": true,
	})
}

func ReplyFriend(c *gin.Context) {
	var req request.ReplyFriendReq

	if err := c.ShouldBind(&req); err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code": 100000,
			"msg":  "验证失败",
			"data": err.Error(),
		})
		return
	}
	if req.Status != 2 && req.Status != 3 {
		c.JSON(http.StatusOK, gin.H{
			"code": 100000,
			"msg":  "该状态不存在",
			"data": nil,
		})
		return
	}
	var user model.User
	dao.GetOneById(req.UserOne, &user)
	if user.Id == 0 {
		c.JSON(http.StatusOK, gin.H{
			"code": 100000,
			"msg":  "用户不存在",
			"data": nil,
		})
		return
	}

	if !dao.IsFriend(c.GetUint("userId"), req.UserOne) {
		c.JSON(http.StatusOK, gin.H{
			"code": 100000,
			"msg":  "已经成为好友不需要申请",
			"data": nil,
		})
		return
	}
	//判断好友申请是否存在
	var friend model.Friend
	dao.GetOneByFields(&model.Friend{
		UserOne: req.UserOne,
		UserTwo: c.GetUint("userId"),
		Status:  1,
	}, &friend)

	if friend.Id == 0 {
		c.JSON(http.StatusOK, gin.H{
			"code": 100000,
			"msg":  "没有好友申请请求",
			"data": nil,
		})
		return
	}
	//根据id和状态修改
	result := dao.Update(&model.Friend{
		Id:     friend.Id,
		Status: req.Status,
	})
	c.JSON(http.StatusOK, gin.H{
		"code": http.StatusOK,
		"msg":  "成功",
		"data": result,
	})
}

func RemoveFriend(c *gin.Context) {

}
